package com.angus.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liyanan
 * @date 2025/08/10 15:24
 * @description
 */
@Slf4j
@Component
public class TerminalUtils {
    /**
     * 从HttpServletRequest中获取终端设备类型
     *
     * @param request HttpServletRequest对象
     * @return 终端设备类型
     */
    public static String getTerminalType(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return "Unknown";
        }
        return parseTerminalType(userAgent);
    }

    /**
     * 根据User-Agent字符串解析终端设备类型
     *
     * @param userAgent User-Agent字符串
     * @return 终端设备类型
     */
    public static String parseTerminalType(String userAgent) {
        if (userAgent == null || userAgent.isEmpty()) {
            return "Unknown";
        }

        String terminal = "PC"; // 默认为PC端
        userAgent = userAgent.toLowerCase();

        // 判断是否为移动端
        if (isMobile(userAgent)) {
            terminal = "Mobile";
        }
        // 判断是否为平板
        else if (isTablet(userAgent)) {
            terminal = "Tablet";
        }

        return terminal;
    }

    /**
     * 判断是否为移动设备
     *
     * @param userAgent User-Agent字符串（小写）
     * @return 是否为移动设备
     */
    private static boolean isMobile(String userAgent) {
        // 常见移动设备标识
        String[] mobileKeywords = {
                "mobile", "android", "iphone", "ipod", "blackberry", "windows phone",
                "opera mini", "iemobile", "mobile safari", "bb10", "playbook", "ucbrowser",
                "nokia", "symbian", "palm", "hiptop", "avantgo", "plucker", "xiino",
                "blazer", "elaine", "windows ce", "mmp", "smartphone", "midp", "wap", "vodafone",
                "o2", "pocket", "kindle", "webos", "playstation vita"
        };

        for (String keyword : mobileKeywords) {
            if (userAgent.contains(keyword)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断是否为平板设备
     *
     * @param userAgent User-Agent字符串（小写）
     * @return 是否为平板设备
     */
    private static boolean isTablet(String userAgent) {
        // 常见平板设备标识
        return userAgent.contains("ipad") ||
                userAgent.contains("tablet") ||
                userAgent.contains("playbook") ||
                (userAgent.contains("android") && !userAgent.contains("mobile"));
    }

}
